package com.mall.shopping.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class StringArrayTypeHandler implements TypeHandler<List<String>> {
    ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        String string = objectMapper.writeValueAsString(strings);
        preparedStatement.setString(i,string);
    }


    @Override
    public List<String> getResult(ResultSet resultSet, String s) throws SQLException {
        String string = resultSet.getString(s);
        String[] strings = string.split(",");
        List<String> list = new ArrayList();
        for (int i = 0; i < strings.length; i++) {
            list.add(strings[i]);
        }
        return list;
    }

    @SneakyThrows
    @Override
    public List<String> getResult(ResultSet resultSet, int i) throws SQLException {
        String string = resultSet.getString(i);
        List list = objectMapper.readValue(string, List.class);
        return list;
    }

    @SneakyThrows
    @Override
    public List<String> getResult(CallableStatement callableStatement, int i) throws SQLException {
        String string = callableStatement.getString(i);
        List list = objectMapper.readValue(string, List.class);
        return list;
    }
}
